#!/bin/sh

earlydie() { echo "$@" >&2; exit 1; }

root=${0%/*}; test -z "$root" && root=. # dirname($0)

test -f "$root/MANIFEST" || earlydie "Can't find MANIFEST, perl-cross is not deployed properly."

abs=`echo "$root" | sed -e 's!^\(.\).*!\1!'`
test "$abs" != '/' && unset abs

if [ -n "$root" -a "$root" != "." -a ! -f "MANIFEST" ]; then
	echo "No MANIFEST found. Assuming out-of-source build."
	echo "Symlinking source files..."

	# perl distribution files are all listed in MANIFEST
	cat "$root/MANIFEST" | sed -e 's/\s.*//' | while read i; do
		d=${i%/*}; test -z "$d" && d=. # dirname($i)
		mkdir -p "$d"
		test "$d" != "." && u=`echo "$d" | sed -e 's![^/]\+!..!g' -e 's!$!/!'` || u=''
		test -n "$abs" && relroot="$root" || relroot="$u$root"
		ln -sf "$relroot/$i" "$i" || earlydie "Symlinking failed."
	done
	
	# perl-cross files are not in MANIFEST
	for i in TESTPACK.px extlibs statars TestInit.pm.testpack \
			make_ext_Makefile.pl miniperl_top Makefile.config.SH \
			Makefile configure; do
		ln -sf "$root/$i" "./$i" || earlydie "Symlinking failed."
	done

	for i in x2p/Makefile utils/Makefile; do
		test -n "$abs" && relroot="$root" || relroot="../$root"
		ln -sf "$relroot/$i" "$i" || earlydie "Symlinking failed."
	done

	# cnf is a special case because we need cnf/diffs to be
	# a proper directory to store locks there
	mkdir cnf
	for i in "$root/cnf/"*; do
		bn=${i##*/}
		test -n "$abs" && rel="" || rel="../"
		test "$bn" != 'diffs' && ln -s "$rel$i" "cnf/$bn"
	done
	cp -a "$root/cnf/diffs" cnf/

	# Make extra sure MANIFEST gets symlinked
	test -f "MANIFEST" || ln -sf "$root/MANIFEST" "./MANIFEST"

	# Dereference any files that will be patched with crosspatch.
	# A better alternative is patch --follow-symlinks,
	# but --follow-symlinks is not widely supported and even when it is,
	# man page discourages its use.
	sed -ne '/^+++ /{s/^+++ //;s/\s.*//;s@^[^/]\+/@@;p}' cnf/diffs/* | while read i; do
		cp -a "$i" "$i.tmp" && rm -f "$i" && cp "$i.tmp" "$i" && rm -f "$i.tmp"
	done

	echo "Symlinking done, proceeding with configure."
fi

cnf/configure "$@"
